var utils = require("./utils");

if (!requestScreenCapture()) {
  toastLog("请求截图权限失败");
  exit();
}
var char_match_map = {
  搜: ["嫂", "樓", "接", "楼"],
  赚: ["廉", "嫌", "賺", "兼"],
  看: ["着", "春"],
  文: ["女"],
  章: ["拿"],
  钱: ["线"],
  觉: ["党"],
  户: ["戶"],
  索: ["素"],
  开: ["升", "研"],
  金: ["全"],
  积: ["枳"],
  币: ["市"],
  现: ["現"],
  领: ["領"],
  读: ["渎"],
  额: ["額"],
  取: ["驭"],
  视: ["规"],
};

var ocrUtils = {
  get_reg_exp(content) {
    var reg_exp_string = content
      .split("")
      .map(function (item) {
        var match = char_match_map[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    var reg_exp = new RegExp(reg_exp_string, "gi");
    console.log("ocrUtils get_reg_exp:", reg_exp.toString());
    return reg_exp;
  },
  capture_screen_then_log_text() {
    var capture_img = captureScreen();
    var capture_img_orc_result = gmlkit.ocr(capture_img, "zh").toArray(3);
    for (var i = 0; i < capture_img_orc_result.length; i++) {
      var item = capture_img_orc_result[i];
      console.log(item.text);
    }
  },
  capture_screen_then_find_by_text(content) {
    return this.capture_screen_then_find_by_reg_exp(this.get_reg_exp(content));
  },
  capture_screen_then_find_by_reg_exp(reg_exp) {
    var capture_img = captureScreen();
    if (!capture_img) {
      toastLog("截图失败");
    }
    var capture_img_orc_result = gmlkit.ocr(capture_img, "zh").toArray(3);

    for (var i = 0; i < capture_img_orc_result.length; i++) {
      var item = capture_img_orc_result[i];
      if (reg_exp.test(item.text)) {
        return item;
      }
    }
  },
  find_text(content) {
    var max_swipe_times = 10;
    var reg_exp = this.get_reg_exp(content);
    while (max_swipe_times > 0) {
      var result = this.capture_screen_then_find_by_reg_exp(reg_exp);
      if (result) {
        return result;
      }
      swipe(
        device.width / 2,
        device.height / 2,
        device.width / 2,
        device.height / 2 - 200,
        500
      );
      max_swipe_times -= 1;
    }
  },
};
